#!/bin/sh
#
# Copyright (C) 2016 Dream Property GmbH
#

source librecovery

FILENAME=${RECOVERY_CACHE}/settings.tar.gz

usage()
{
	echo "Usage: ${0} [-hqtv] [<settings.tar.gz>]"
	echo "       Default: ${FILENAME}"
	exit ${1}
}

xgetopts $@

shift $((${OPTIND} - 1))
[ "$#" -le 1 ] || usage 1
[ "$#" -eq 0 ] || FILENAME=`xrealpath ${1}`

assert_rescue_mode
create_workspace

safe_mount "${ROOT_PARTITION}" "${ROOT_MOUNTPOINT}" -o ro || abort "Failed to mount root filesystem"
if is_beneath_directory "${FILENAME}" "${DATA_MOUNTPOINT}"; then
	safe_mount "${DATA_PARTITION}" "${DATA_MOUNTPOINT}" || abort "Failed to mount data filesystem"
fi

mkdir -p backup-lists.d tmp/.recovery
cd "${ROOT_MOUNTPOINT}"
for dir in "${RECOVERY_CACHE}" "${ROOT_MOUNTPOINT}/etc/recovery"; do
	if [ -d "${dir}/backup-hooks.d" ]; then
		find "${dir}/backup-hooks.d" -maxdepth 1 -type f -perm +0100 -print0 \
			| sort -z \
			| ACTION="backup" \
			  FILESDIR="${WORKSPACE}/tmp/.recovery" \
			  LISTSDIR="${WORKSPACE}/backup-lists.d" \
			  SYSROOT="${ROOT_MOUNTPOINT}" \
			  xargs -0 -r -n1 /bin/sh -c
	fi
done
cd "${OLDPWD}"

BACKUP_PATHS="
/etc/dropbear/
/etc/enigma2/
/etc/exports
/etc/hostname
/etc/machine-id
/etc/recovery/
/etc/videomode
/root/.ssh/
/usr/share/enigma2/picon/
/var/lib/connman/
/tmp/.recovery/
$(grep -hs '^/' "${ROOT_MOUNTPOINT}/etc/recovery"/backup-lists.d/*.list || true)
$(grep -hs '^/' "${RECOVERY_CACHE}"/backup-lists.d/*.list || true)
$(grep -hs '^/' "${WORKSPACE}"/backup-lists.d/*.list || true)
"
printf "${BACKUP_PATHS}" >"tmp/.recovery/backup-paths.bak"
sed -n -e 's,^root:\([^:]*\):.*,\1,p' "${ROOT_MOUNTPOINT}/etc/shadow" >"tmp/.recovery/pwhash-root.bak"
(cd "${ROOT_MOUNTPOINT}/var/lib/dpkg/info" && ls -1 *.list) | sed -e 's,\.list$,,' > "tmp/.recovery/packages.bak"
safe_mount tmp "${ROOT_MOUNTPOINT}/tmp" -o bind || warn "Failed to mount ${ROOT_MOUNTPOINT}/tmp - using local tmp"
create_tarball "${ROOT_MOUNTPOINT}" "${FILENAME}" "${BACKUP_PATHS}" || abort "Failed to create ${FILENAME}"
